package com.wx_shop.api.util.wx.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wx_shop.api.comm.Constants;
import com.wx_shop.api.util.wx.dto.WeixinPayDomain;
import com.wx_shop.api.util.wx.dto.WeixinSign;

public class WeixinUtil {

	static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);
	
	public static boolean checkSignature(String token, String timestamp, String nonce, String signature) {

		logger.info("token={}, timestamp={}, nonce={}, signature={}", token, timestamp, nonce, signature);
		
		List<String> list = new ArrayList<String>();
		list.add(token);
		list.add(timestamp);
		list.add(nonce);

		Collections.sort(list);

		String str = StringUtils.join(list.toArray());
		
		logger.info("str={}", str);
		
		String sha1Str = SHA1(str);
		
		logger.info("str={}, SHA1={}, signature={}", str, sha1Str, signature);
		
		return signature.equals(sha1Str);
	}

	public static String getSignatureByList(Map<String, Object> params) {
		List<String> list = new ArrayList<String>();
		for(String key : params.keySet()) {
			list.add(key + "=" + params.get(key));
		}
		
		Collections.sort(list);

		String str = StringUtils.join(list.toArray(), "&");
		String sha1Str = SHA1(str);
		return sha1Str;
	}
	
	// 微信支付 - 签名校验
	public static String weixinPaySign(Map<String, Object> params, String lastStr) {
		List<String> list = new ArrayList<String>();
		for(String key : params.keySet()) {
			list.add(key + "=" + params.get(key));
		}
		
		Collections.sort(list);

		String str = StringUtils.join(list.toArray(), "&");
		str = str + lastStr;
		
		logger.debug("str={}", str);
		String md5Str = MD5(str);
		logger.debug("md5Str={}", md5Str);
		
		return md5Str;
	}
		
	// 微信支付 - 签名校验
	public static String weixinPaySign(WeixinSign weixinSign, String lastStr) {
		Map<String, Object> params = new HashMap<String, Object>();
		Field[] fields = weixinSign.getClass().getDeclaredFields();
		for(int i=0; i<fields.length; i++) {
			Field f = fields[i];
			
			try {
				String name = f.getName();
				Object value = f.get(weixinSign);
				logger.debug("weixinPaySign param:name={}, value={}", name, value);
				
				if(value != null && StringUtils.isNotEmpty(value.toString())) {
					params.put(name, value);
				}
			} catch (Exception e) {
				logger.error("e={}", e);
			} 
		}
		return weixinPaySign(params, lastStr);
	}
	
	public static String getWXAuthUrl(HttpServletRequest request, WeiXinScopeType scop) {
		String currUrl = request.getScheme() + "://" + request.getServerName();
		int port = request.getServerPort();
		if(port != 80) {
			currUrl = currUrl + ":" + port;
		}
		currUrl = currUrl + request.getRequestURI();

		String queryStr = request.getQueryString();
		if(StringUtils.isNotEmpty(queryStr)) {
			currUrl = currUrl + "?" + queryStr;
		}
		
		logger.info("AuthUrl01={}", currUrl);
		
		try {
			currUrl = URLEncoder.encode(currUrl, "utf-8");
			
			logger.info("AuthUrl01={}", currUrl);
			
			String url = Constants.AUTHORIZE;
			url = url.replace("{redirect_uri}", currUrl);
			url = url.replace("{scope}", scop.name());
			
			logger.info("AuthUrl03={}", url);
			
			return url;
		} catch (Exception e) {
			logger.error("e={}", e);
		}
		return null;
	}
	
	
	public static String SHA1(String decript) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			logger.error("e={}", logger);
		}
		return "";
	}
	
	public static String SHA(String decript) {
		try {
			MessageDigest digest = java.security.MessageDigest
					.getInstance("SHA");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String MD5(String input) {
		try {
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(input.getBytes());
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < md.length; i++) {
				String shaHex = Integer.toHexString(md[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param password
	 *            加密密码
	 * @return
	 */
	public static byte[] encryptAES(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 */
	public static byte[] decryptAES(byte[] content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// 微信类型 
	public static enum WeiXinScopeType {
		snsapi_userinfo, snsapi_base;
	}
	
	public static void main(String[] args) {
		
		WeixinPayDomain wxPayDomain = new WeixinPayDomain();
		wxPayDomain.appid = "fdsafds";
		wxPayDomain.attach = "fdsafds";
		System.out.println(weixinPaySign(wxPayDomain, "fdsafs"));
	}
}

